"use client"

import { useContext, useState } from "react"
import { useRouter } from "next/navigation"
import Image from "next/image"
import { UserContext } from "@/app/layout"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Card, CardContent, CardFooter } from "@/components/ui/card"
import { Checkbox } from "@/components/ui/checkbox"
import { Plus, Search, Filter, Edit, Trash2, ShoppingCart, Info } from "lucide-react"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import { Badge } from "@/components/ui/badge"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Slider } from "@/components/ui/slider"
import { Label } from "@/components/ui/label"

// Mock product data
const mockProducts = [
  {
    id: "1",
    name: "珍珠项链",
    code: "XL251231093",
    price: 1299,
    image: "/placeholder.svg?height=200&width=200",
    category: "项链",
    pearlColor: "白色",
    warehouse: "主仓",
    isStoreOnly: false,
  },
  {
    id: "2",
    name: "珍珠耳环",
    code: "EH251231094",
    price: 899,
    image: "/placeholder.svg?height=200&width=200",
    category: "耳环",
    pearlColor: "粉色",
    warehouse: "主仓",
    isStoreOnly: false,
  },
  {
    id: "3",
    name: "珍珠手链",
    code: "SL251231095",
    price: 799,
    image: "/placeholder.svg?height=200&width=200",
    category: "手链",
    pearlColor: "黑色",
    warehouse: "门店",
    isStoreOnly: true,
  },
  {
    id: "4",
    name: "珍珠戒指",
    code: "JZ251231096",
    price: 1599,
    image: "/placeholder.svg?height=200&width=200",
    category: "戒指",
    pearlColor: "金色",
    warehouse: "主仓",
    isStoreOnly: false,
  },
]

export default function ProductList() {
  const { userRole } = useContext(UserContext)
  const router = useRouter()
  const [searchTerm, setSearchTerm] = useState("")
  const [showFilters, setShowFilters] = useState(false)
  const [selectedProducts, setSelectedProducts] = useState<string[]>([])
  const [filters, setFilters] = useState({
    category: "",
    pearlColor: "",
    priceRange: [0, 2000] as [number, number],
  })

  const isEmployee = userRole === "employee" || userRole === "admin"

  // Filter products based on search term, filters, and user role
  const filteredProducts = mockProducts.filter((product) => {
    // Hide store-only products from customers
    if (product.isStoreOnly && userRole === "customer") return false

    // Apply search filter
    if (searchTerm && !product.name.includes(searchTerm) && !product.code.includes(searchTerm)) {
      return false
    }

    // Apply category filter
    if (filters.category && product.category !== filters.category) {
      return false
    }

    // Apply pearl color filter
    if (filters.pearlColor && product.pearlColor !== filters.pearlColor) {
      return false
    }

    // Apply price range filter
    if (product.price < filters.priceRange[0] || product.price > filters.priceRange[1]) {
      return false
    }

    return true
  })

  const handleSelectProduct = (id: string) => {
    setSelectedProducts((prev) => (prev.includes(id) ? prev.filter((productId) => productId !== id) : [...prev, id]))
  }

  const handleAddToCart = (ids: string[]) => {
    // In real app, add to cart logic
    console.log("Adding to cart:", ids)
    // Show success message
    alert(`已将${ids.length}个商品加入货盘`)
    // Clear selection
    setSelectedProducts([])
  }

  const handleDeleteProduct = (id: string) => {
    // In real app, delete product logic
    console.log("Deleting product:", id)
    // Show success message
    alert("商品已删除")
  }

  const handleCreateProduct = () => {
    router.push("/product/create")
  }

  const handleEditProduct = (id: string) => {
    router.push(`/product/edit/${id}`)
  }

  const handleViewProduct = (id: string) => {
    router.push(`/product/${id}`)
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center gap-2">
        <div className="relative flex-1">
          <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
          <Input
            type="search"
            placeholder="搜索商品名称或编号..."
            className="pl-8"
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
          />
        </div>
        <Button variant="outline" size="icon" onClick={() => setShowFilters(!showFilters)}>
          <Filter className="h-4 w-4" />
        </Button>
        {isEmployee && (
          <Button onClick={handleCreateProduct}>
            <Plus className="h-4 w-4 mr-2" />
            新建商品
          </Button>
        )}
      </div>

      {showFilters && (
        <Card>
          <CardContent className="p-4 grid gap-4">
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="category">类别</Label>
                <Select value={filters.category} onValueChange={(value) => setFilters({ ...filters, category: value })}>
                  <SelectTrigger id="category">
                    <SelectValue placeholder="选择类别" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">全部</SelectItem>
                    <SelectItem value="项链">项链</SelectItem>
                    <SelectItem value="耳环">耳环</SelectItem>
                    <SelectItem value="手链">手链</SelectItem>
                    <SelectItem value="戒指">戒指</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label htmlFor="pearlColor">珍珠颜色</Label>
                <Select
                  value={filters.pearlColor}
                  onValueChange={(value) => setFilters({ ...filters, pearlColor: value })}
                >
                  <SelectTrigger id="pearlColor">
                    <SelectValue placeholder="选择颜色" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">全部</SelectItem>
                    <SelectItem value="白色">白色</SelectItem>
                    <SelectItem value="粉色">粉色</SelectItem>
                    <SelectItem value="黑色">黑色</SelectItem>
                    <SelectItem value="金色">金色</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
            <div className="space-y-2">
              <div className="flex justify-between">
                <Label>价格范围</Label>
                <span className="text-sm text-muted-foreground">
                  ¥{filters.priceRange[0]} - ¥{filters.priceRange[1]}
                </span>
              </div>
              <Slider
                defaultValue={[0, 2000]}
                max={2000}
                step={100}
                value={filters.priceRange}
                onValueChange={(value) => setFilters({ ...filters, priceRange: value as [number, number] })}
              />
            </div>
          </CardContent>
          <CardFooter className="flex justify-end gap-2 border-t p-4">
            <Button
              variant="outline"
              onClick={() => setFilters({ category: "", pearlColor: "", priceRange: [0, 2000] })}
            >
              重置
            </Button>
            <Button onClick={() => setShowFilters(false)}>应用筛选</Button>
          </CardFooter>
        </Card>
      )}

      {selectedProducts.length > 0 && (
        <div className="flex items-center justify-between bg-muted p-2 rounded-lg">
          <span>已选择 {selectedProducts.length} 件商品</span>
          <Button onClick={() => handleAddToCart(selectedProducts)}>
            <ShoppingCart className="h-4 w-4 mr-2" />
            加入货盘
          </Button>
        </div>
      )}

      <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
        {filteredProducts.map((product) => (
          <Card key={product.id} className="overflow-hidden">
            <div className="relative">
              <Image
                src={product.image || "/placeholder.svg"}
                alt={product.name}
                width={200}
                height={200}
                className="w-full h-40 object-cover"
              />
              {product.isStoreOnly && <Badge className="absolute top-2 right-2">门店专供</Badge>}
              <div className="absolute top-2 left-2">
                <Checkbox
                  checked={selectedProducts.includes(product.id)}
                  onCheckedChange={() => handleSelectProduct(product.id)}
                />
              </div>
            </div>
            <CardContent className="p-3">
              <h3 className="font-medium truncate">{product.name}</h3>
              <p className="text-sm text-muted-foreground truncate">{product.code}</p>
              <p className="font-bold text-primary">¥{product.price}</p>
            </CardContent>
            <CardFooter className="p-3 pt-0 flex gap-2">
              <Button variant="outline" size="sm" className="flex-1" onClick={() => handleViewProduct(product.id)}>
                <Info className="h-3 w-3 mr-1" />
                详情
              </Button>
              {isEmployee && (
                <Button variant="outline" size="sm" onClick={() => handleEditProduct(product.id)}>
                  <Edit className="h-3 w-3" />
                </Button>
              )}
              {isEmployee && (
                <Dialog>
                  <DialogTrigger asChild>
                    <Button variant="outline" size="sm">
                      <Trash2 className="h-3 w-3" />
                    </Button>
                  </DialogTrigger>
                  <DialogContent>
                    <DialogHeader>
                      <DialogTitle>确认删除</DialogTitle>
                      <DialogDescription>您确定要删除商品 "{product.name}" 吗？此操作无法撤销。</DialogDescription>
                    </DialogHeader>
                    <div className="flex justify-end gap-2">
                      <Button variant="outline">取消</Button>
                      <Button variant="destructive" onClick={() => handleDeleteProduct(product.id)}>
                        确认删除
                      </Button>
                    </div>
                  </DialogContent>
                </Dialog>
              )}
            </CardFooter>
          </Card>
        ))}
      </div>

      {filteredProducts.length === 0 && (
        <div className="text-center py-8">
          <p className="text-muted-foreground">没有找到符合条件的商品</p>
        </div>
      )}
    </div>
  )
}

